package com.hjt.gulimall.cart.controller;

import com.hjt.common.constant.CartConstant;
import com.hjt.gulimall.cart.interceptor.CartInterceptor;
import com.hjt.gulimall.cart.service.CartService;
import com.hjt.gulimall.cart.vo.Cart;
import com.hjt.gulimall.cart.vo.CartItem;
import com.hjt.gulimall.cart.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * @author:97007
 * @date:2021/10/1 9:47
 */
@Controller
public class CartController {

    @Autowired
    private CartService cartService;


    @ResponseBody
    @GetMapping("/getCartItem")
    public List<CartItem> getCartItemList() {
        return cartService.getCartItemList();
    }

    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuId") Long skuId, @RequestParam("checked") Boolean checked) {

        cartService.checked(skuId, checked);

        return "redirect:http://cart.gulimall.com/cart.html";
    }


    /**
     * 添加商品到购物车
     *  RedirectAttributes 重定向携带数据
     *  redirectAttributes.addFlashAttribute() 将数据放到session中，但是只能取一次
     *  addAttribute() 将数据放到url中
     * @return
     */
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("count") Integer count, RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {
        cartService.addToCart(skuId, count);

        // 使用用重定向，防止用户刷新页面重复提交加入购物车请求
        redirectAttributes.addAttribute("skuId", skuId);
        return "redirect:http://cart.gulimall.com/addToCart.html";
    }


    // 用户刷新加入购物车页面时，每次都去请求购物车信息
    @GetMapping("/addToCart.html")
    public String addToCartSuccessPage(@RequestParam(value = "skuId",required = false) Long skuId, Model model) {
        if (skuId != null) {
            CartItem cartItem = cartService.getCartItem(skuId);
            model.addAttribute("item", cartItem);
        }
        return "success";
    }

    // 查询购物车
    @GetMapping("/cart.html")
    public String getCart(Model model) throws ExecutionException, InterruptedException {
        model.addAttribute("item", cartService.getCart());
        return "cartList";
    }

}
